use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

#[derive(Deserialize, Debug)]
pub struct JsonRpcRequest {
    pub jsonrpc: String,
    pub method: String,
    pub params: Option<Value>,
    pub id: Option<Value>,
}
#[derive(Serialize,Debug)]
pub struct JsonRpcResponse {
    pub jsonrpc: String,
    pub result: Option<Value>,
    pub error: Option<JsonRpcError>,
    pub id: Option<Value>,
}
#[derive(Serialize,Debug)]
pub struct JsonRpcError {
    pub code: i32,
    pub message: String,
    pub data: Option<Value>,
}
pub fn create_error_response(id:u64,code: i32, message: &str) -> JsonRpcResponse {
    JsonRpcResponse {
        jsonrpc: "2.0".to_string(),
        result: None,
        error: Some(JsonRpcError {
            code,
            message: message.to_string(),
            data: None,
        }),
        id:Some(serde_json::to_value(id).unwrap()),
    }
}

use common_lib;
use common_lib::ErrorCode;

pub fn create_error_response_use_code(id:u64,error_code:&ErrorCode) -> JsonRpcResponse {
    JsonRpcResponse {
        jsonrpc: "2.0".to_string(),
        result: None,
        error: Some(JsonRpcError {
            code: error_code.code(),
            message: error_code.message().to_string(),
            data: None,
        }),
        id:Some(serde_json::to_value(id).unwrap()),
    }
}


// 用于调试输出信息
pub fn iterate_params(request: &JsonRpcRequest) -> Result<(), String> {
    let params = match &request.params {
        Some(Value::Array(arr)) => arr,
        _ => return Err("Expected array params".to_string())
    };

    for param in params {
        match param {
            Value::String(s) => println!("String param: {}", s),
            Value::Number(n) => println!("Number param: {}", n),
            Value::Bool(b) => println!("Boolean param: {}", b),
            _ => println!("Other type param: {:?}", param),
        }
    }

    Ok(())
}
